package com.zoro.barn.commons.webcommons.webconfig;

import com.zoro.barn.commons.webcommons.response.advice.ResponseLogAdvice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author zhaoxingwu
 */
public class ResponseLogConfig {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final ResponseLogAdvice responseLogAdvice = new ResponseLogAdvice();

    @Bean("responseFormatAdvice")
    public ResponseBodyAdvice responseBodyAdvice() {
        logger.info(" response body logger loaded ");
        return new NestedResponseLogAdvice();
    }


    @RestControllerAdvice
    @Order(300)
    private class NestedResponseLogAdvice implements ResponseBodyAdvice<Object> {


        @Override
        public boolean supports(MethodParameter returnType, Class converterType) {
            return responseLogAdvice.supports(returnType, converterType);
        }

        @Override
        public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                      Class selectedConverterType, ServerHttpRequest request,
                                      ServerHttpResponse response) {

            return responseLogAdvice.beforeBodyWrite(body, returnType, selectedContentType, selectedConverterType,
                    request, response);
        }

    }
}
